package cn.com.scitc.loginservlet;

import cn.com.scitc.dao.ManagerDao;
import cn.com.scitc.model.Manager;
import cn.com.scitc.server.MyMd5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Calendar;

@WebServlet(name = "CheckLoginServlet",urlPatterns = "/manager/checkLogin")
public class CheckLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String loginId = request.getParameter("loginId");
        String pwd = request.getParameter("pwd");
        boolean result = MyMd5.validateManager(loginId, pwd);

        System.out.println(result);
        if(result){
            final HttpSession session = request.getSession();
            ManagerDao managerDao = new ManagerDao();
            final Manager manager = managerDao.findByLoginId(loginId);

            if (manager.getLogincount() == null){
                manager.setLogincount(1);
            }else {
                manager.setLogincount(manager.getLogincount() + 1);
            }
            session.setAttribute("currentUser",manager);

            Calendar calendar = Calendar.getInstance();
            manager.setLogindate(calendar.getTime());
            managerDao.updateByPrimaryKey(manager);

            String realName;
            realName = manager.getRealname();
            session.setAttribute("realUserName",realName);

            response.sendRedirect("./home");
//            System.out.println("访问成功！！");
        }else {
            //绑定页面
//            request.getRequestDispatcher("/WEB-INF/loginIndex.jsp").forward(request, response);
            //跳转页面
            request.getSession().setAttribute("loginMsg","用户名或密码错误！");
            response.sendRedirect("./login");
//            response.sendRedirect("./login?error=yes");
        }
    }

}
